package ph.com.gs3.formalistics.model.dao;

import ph.com.gs3.formalistics.model.DatabaseHelper;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public abstract class SQLiteDataAccessObject extends DataAccessObject {

	public static final String TAG = SQLiteDataAccessObject.class.getSimpleName();

	// Database Fields
	protected SQLiteDatabase database;
	protected DatabaseHelper databaseHelper;

	public SQLiteDataAccessObject(DatabaseHelper databaseHelper) {
		super(databaseHelper.getContext());
		this.databaseHelper = databaseHelper;
	}

	public SQLiteDataAccessObject(Context context) {
		super(context);
		databaseHelper = new DatabaseHelper(context);
	}

	public void open() throws SQLException {
		database = databaseHelper.getWritableDatabase();
	}

	public void close() {
		databaseHelper.close();
	}

	public String generateSelectClauseFromArray(String[] columns) {

		String selectClause = "";

		for (String column : columns) {
			selectClause += column + ", ";
		}

		selectClause = selectClause.substring(0, selectClause.length() - 2);

		return selectClause;

	}

	// ========================================================================
	// {{ Exceptions

	public static class DAOClosedException extends Exception {
		private static final long serialVersionUID = -2040640986487604192L;

		public DAOClosedException() {
			super("Attempt to use a DAO without opening it.");
		}

	}

	public static class InsertFailedException extends Exception {

		private static final long serialVersionUID = 7758948494925874048L;

		public InsertFailedException(Throwable throwable) {
			super(throwable);
		}

		public InsertFailedException(String details) {
			super(details);
		}

		public InsertFailedException() {
			super();
		}
	}

	public static class UpdateFailedException extends Exception {

		private static final long serialVersionUID = 3080928587926432620L;

		public UpdateFailedException(Throwable throwable) {
			super(throwable);
		}

		public UpdateFailedException(String message) {
			super(message);
		}

	}

	public static class DeleteFailedException extends Exception {

		private static final long serialVersionUID = 740825541977963443L;

		public DeleteFailedException(String message) {
			super(message);
		}

		public DeleteFailedException(Throwable throwable) {
			super(throwable);
		}

		public DeleteFailedException(String message, Throwable throwable) {
			super(message, throwable);
		}

	}

	// }}

}
